<?php

namespace app\api\controller;

use app\admin\model\config\Basics;
use app\admin\model\user\Address;
use app\common\controller\Api;
use app\common\handler\TimeHandler;
use app\common\model\MoneyLog;
use app\common\model\User;
use think\Db;
use think\Model;

/**
 * 个人中心
 */
class Center extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];

    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 地址列表
     */
    public function addressList()
    {
        $user = $this->auth->getUserinfo();
        $list =  Address::Where('uid',$user['id'])->select();
        $this->success('successful', $list);
    }

    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 添加和修改地址
     */
    public function addressAddUpd()
    {
        $user = $this->auth->getUserinfo();

        $validate = new \think\Validate([
            ['name', 'require', '收货人不能为空'],
            ['mobile', 'require', '电话号码不能为空'],
            ['gender', 'require', '性别不能为空'],
//            ['province', 'require', '省份不能为空'],
//            ['city', 'require', '市不能为空'],
//            ['area', 'require', '区域不能为空'],
            ['receipt_address', 'require', '收货地址不能为空'],
            ['lng', 'require', '经纬度不能为空'],
            ['lat', 'require', '经纬度不能为空'],
        ]);
        if (!$validate->check(input())) {
            $this->error('提交失败：' . $validate->getError());
        }

        $is_default = $this->request->param('is_default',2);
        $data=[
            'name'=>$this->request->param('name'),
            'mobile'=>$this->request->param('mobile'),
            'gender'=>$this->request->param('gender'),
            'province'=>$this->request->param('province',0),
            'city'=>$this->request->param('city',0),
            'area'=>$this->request->param('area',0),
            'receipt_address'=>$this->request->param('receipt_address'),
            'address'=>$this->request->param('address'),
            'is_default'=>$is_default,
            'lng'=>$this->request->param('lng'),
            'lat'=>$this->request->param('lat'),
        ];

        if($is_default == 1){
            Address::update(['is_default'=>2],['uid'=>$user['id']]);
        }
        $id = $this->request->param('id');
        if($id){
          $result =  Address::update($data,['id'=>$id,'uid'=>$user['id']]);
          if(!$result){
              $this->success('没有更新');
          }
        }else{
            $data['uid']=$user['id'];
            $data['create_time']=time();
          $result =  Address::create($data);
        }
        if($result){
            $this->success('设置成功');
        }
        $this->error('设置失败');
    }


    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 删除地址
     */
    public function addressDel()
    {
        $user = $this->auth->getUserinfo();
        $id = $this->request->param('id');
        $result = Address::where(['id'=>$id,'uid'=>$user['id']])->delete();
        if($result){
            $this->success('删除成功');
        }
        $this->error('删除失败');
    }


    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 地址详情
     */
    public function addressDetail()
    {
        $user = $this->auth->getUserinfo();
        $id = $this->request->param('id');
        $result = Address::get(['id'=>$id,'uid'=>$user['id']]);
        if($result){
            $this->success('获取成功',$result);
        }
        $this->error('获取失败');
    }

    /**
     * @throws \think\exception\DbException
     * 收益明细
     */
    public function profitList()
    {
        $user = $this->auth->getUser();
        $page = $this->request->param('page',1);//页码
        $pageSize = $this->request->param('pageSize',10);//每页展示数量
//        `type` int(2) DEFAULT NULL COMMENT '收入类型 1订单回购 2游戏pk 3订单分销 4提现',
        $model = (new MoneyLog())
            ->field('id,type,money,memo,status,createtime')
            ->where('user_id',$user['id'])
            ->where('type','not null')
            ->where('status','not in',['1','3'])
            ->order('createtime desc')
            ->paginate($pageSize, '', ['page' => $page, 'list_rows' => $pageSize]);
        $total= $model->total();
        $list =  $model->items();
        if($list){
            foreach ($list as $v){
                $v['createtime'] =TimeHandler::getStrtotimeDate($v['createtime']);
            }
        }
        $info = Basics::get(['id'=>1]);
        $this->success('successful', ['list'=>["total" =>$total , "list" => $list],'all_money'=>$user->money,'withdrawal_interdict'=>$info['withdrawal_interdict']]);
    }

    /**
     * @throws \think\exception\DbException
     * 提现
     */
    public function balanceWithdrawal()
    {
        $info = Basics::get(['id'=>1]);
        $user = $this->auth->getUser();
        $price = $this->request->param('price');//提现金额
        if($price <= 0){
            $this->error('提现金额要大于0');
        }
        if($price > $user->money){
            $this->error('提现余额不足');
        }
        if($info['withdrawal_interdict'] >=0 && $info['withdrawal_interdict'] < $price){
            $this->error('提现金额必须大于等于'.$info['withdrawal_interdict']);
        }
        $accountInfo = Db::name('user_tx_account')->where('uid',$user['id'])->find();
        if(!$accountInfo){
            $this->error('未添加提现信息');
        }
        $result = false;
        Db::startTrans();
        try {
            $data =[
                'uid'=>$user['id'],
                'type'=>'1',  //提现类型:1=银行提现 ,2=微信提现'
                'tx_number'=> "tx".time().rand(100000,999999),//提现单号
                'actual_price'=>$price,
                'payee_name'=>$accountInfo['name'], //收款人姓名
                'bank_name'=>$accountInfo['bank_name'], //提现银行
                'account'=>$accountInfo['account'], //提现账户
                'status'=>1,
                'create_time'=>date('Y-m-d H:i:s')
            ];
            $res = \app\admin\model\usertx\Record::create($data);
            $result = user::money(-$price,$user['id'],'提现',4,$res['id']);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }

        if($result){
            $this->success('提现申请成功');
        }
        $this->error('提现申请失败');
    }


    /**
     * @throws \think\exception\DbException
     * 提现账户新增修改
     */
    public function bindTxAccount()
    {
        $user = $this->auth->getUser();

        $validate = new \think\Validate([
            ['name', 'require', '收款人姓名不能为空'],
            ['account', 'require', '账户不能为空'],
            ['bank_name', 'require', '银行名称不能为空'],
            ['bank_address', 'require', '开户行不能为空'],
        ]);
        if (!$validate->check(input())) {
            $this->error('提交失败：' . $validate->getError());
        }
        $data=[
            'name'=>$this->request->param('name'),
            'account'=>$this->request->param('account'),
            'bank_name'=>$this->request->param('bank_name'),
            'bank_address'=>$this->request->param('bank_address'),
        ];
        $account = Db::name('user_tx_account')->where(['uid'=>$user['id']])->find();
        if($account){
            $result =  Db::name('user_tx_account')->where(['uid'=>$user['id']])->update($data);
            if(!$result){
                $this->success('没有更新');
            }
        }else{
            $data['uid']=$user['id'];
            $data['create_time']=time();
            $result =  Db::name('user_tx_account')->insert($data);
        }
        if($result){
            $this->success('设置成功');
        }
        $this->error('设置失败');

    }




    /**
     * @throws \think\exception\DbException
     * 提现账户信息
     */
    public function bindTxAccountInfo()
    {
        $user = $this->auth->getUser();
        $result =  Db::name('user_tx_account')->where(['uid'=>$user['id']])->find();
        $this->success('提现账户信息',$result);

    }





    


}
